import React, { Component, PureComponent } from 'react';
import { Button, Form, Icon, Input, Popover, Spin, Tag } from 'antd';
import { getRandomKey, isObjectHadEmpty, isObjectValEqual, isObjectValueEmpty, sleepFunc } from '/common/utils/utils';
import forEach from 'lodash/forEach';
import isArray from 'lodash/isArray';
import isEmpty from 'lodash/isEmpty';
import isFunction from 'lodash/isFunction';
import isString from 'lodash/isString';
import map from 'lodash/map';

const { Group } = Input;

@Form.create()
export class SearchFormComp extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      formData: props.formData ? props.formData : {},//用于临时保存表单数据
    };
  }

  componentDidMount() {
    if (this.props.onRef) this.props.onRef(this);
  }

  componentDidUpdate(prevProps, prevState) {
    if (!isObjectValEqual(prevProps.formData, this.props.formData)) {
      this.setState({ formData: this.props.formData });
    }
  }

  updateFormData(newFormData, afterCb) {
    this.setState({
      formData: {
        ...this.state.formData,
        ...newFormData,
      },
    }, () => {
      afterCb && afterCb(this.state.formData);
    });
  }

  deleteFields(fields) {
    let fArr = [];
    if (isArray(fields)) {
      fArr = fields;
    } else if (isString(fields)) {
      fArr = fields.split(';');
    }
    let tmpObj = {};
    forEach(fArr, v => {
      if (v) {
        tmpObj[v] = null;
      }
    });
    this.props.form.setFieldsValue(tmpObj);
    this.handleOk();
  }


  validateForm(okCb, errCb) {
    const { form } = this.props;
    form.validateFieldsAndScroll((errors, fieldsValue) => {
      if (isEmpty(errors)) {
        okCb && okCb(fieldsValue);
      } else if (errCb) {
        errCb && errCb(errors, fieldsValue);
      }
    });
  }

  /**
   * 确认
   */
  handleOk(e, isCancel) {
    const { onOk, onError } = this.props;
    this.validateForm((fieldsValue) => {
      this.setState({ formData: fieldsValue }, () => {
        const reValues = this.childFormRef.getAjaxData(fieldsValue);
        if (false === reValues) return false;
        isFunction(onOk) && (onOk(reValues, fieldsValue, isCancel));
      });
    }, onError);
  }

  /**
   * 取消
   */
  handleCancel() {
    this.props.form.resetFields();
    // if (this.props.multiAct) {
      isFunction(this.props.onCancel) && (this.props.onCancel());
    // } else {
    //   this.handleOk(null, true);
    // }
  }

  /**
   * 重置
   */
  handleReset() {
    const { onReset } = this.props;
    this.setState({
      formData: {},
    }, () => {
      this.props.form.resetFields();
      if (onReset) {
        onReset();
      }
    });
  }

  render() {
    const childrenComp = React.cloneElement(this.props.children, {
      onRef: (ref) => {
        this.childFormRef = ref;
      },
      parentRef: this,
      updateFormData: this.updateFormData.bind(this),
      formData: this.state.formData,
      form: this.props.form,
    });
    const formProps = {
      labelCol: { span: 7 },
      wrapperCol: { span: 17 },
    };
    return (
      <Form className={'form-small'} labelAlign='left' layout="horizontal" {...formProps}>
        {childrenComp}
        <div style={{ textAlign: 'center', paddingTop: 16, borderTop: '1px solid #e0e0e0' }}>
          <Group>
            <Button type='primary' htmlType="submit"
                    onClick={this.handleOk.bind(this)}>{this.props.multiActTxt || '查询'}</Button>
            <Button onClick={this.handleCancel.bind(this)}>取消</Button>
            <Button onClick={this.handleReset.bind(this)}>重置</Button>
          </Group>
        </div>
      </Form>
    );
  }
}

const tagStyle = {
  marginTop: 4,
  borderRadius: 0,
};
const tagSpanStyle = {
  // maxWidth: 150,
  display: 'inline-block',
  overflow: 'hidden',
  float: 'left',
  textOverflow: 'ellipsis',
};

class SearchComp extends PureComponent {

  constructor(props) {
    super(props);
    const { formData } = props;
    this.formData = formData ? { ...formData } : {};
    this.popoverZIndex = props.defaultOpen ? 999 : -1; // 浮层的 z-index 值，999 表示可见，-1 则一直隐藏
    this.state = {
      isOpen: true,
    };
  }

  componentDidMount() {
    // 由于搜索表单的浮层默认是打开状态且隐藏起来的，所以如果 this.props.defaultOpen 是关闭的话，就把浮层关闭
    if (!this.props.defaultOpen) {
      sleepFunc(300).then(() => {
        if (!this.props.defaultOpen) {
          this.setState({ isOpen: false });
          this.popoverZIndex = 999;
        }
      });
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevProps.defaultOpen !== this.props.defaultOpen) {
      this.popoverZIndex = this.props.defaultOpen ? 999 : -1;
      this.setState({
        isOpen: this.props.defaultOpen,
      });
    }

    if (!isObjectValEqual(prevProps.formData, this.props.formData)) {
      this.formData = this.props.formData || {};
      this.setState({ randomKey: getRandomKey() });
    }
  }

  deleteSearchFields(fields, e) {
    e.stopPropagation();
    e.preventDefault();
    // let fArr = [];
    // if (isArray(fields)) {
    //   fArr = fields;
    // } else if (isString(fields)) {
    //   fArr = fields.split(';');
    // }
    // forEach(fArr, v => {
    //   // if (this.formData.hasOwnProperty(v)) {
    //   this.formData[v] = null;
    //   // }
    // });
    this.searchRef.deleteFields(fields);
  }

  render() {
    const { popoverProps } = this.props;
    const previewFields = this.props.getPreviewData ? this.props.getPreviewData(this.formData) : [
      // {
      //   label: '会计期间',
      //   fieldNames: 'beginPeriod;endPeriod',
      //   text: '2019-06-10 至 2019-06-17',
      // }, {
      //   label: '科目',
      //   fieldNames: 'items',
      //   text: 'KM0001 科目0001',
      // },
    ];
    const formContent = (
      <SearchFormComp
        onRef={(ref) => {
          this.searchRef = ref;
        }}
        formData={this.props.formData}
        multiAct={this.props.multiAct}
        multiActTxt={this.props.multiActTxt}
        onOk={(values, originalValues, isCancel) => {

          this.formData = { ...originalValues };
          if(false === this.props.multiAct) {
            this.setState({
              isOpen: false,
              randomKey: getRandomKey()
            }, () => {
              if (true !== isCancel) {
                sleepFunc(300).then(() => {
                  this.props.onOk && this.props.onOk(values, originalValues);
                });
              }
            });
          } else {
            this.props.onOk && this.props.onOk(values, originalValues);
          }
        }}
        onReset={() => {
          for (let k in this.formData) {
            this.formData[k] = null;
          }
          this.setState({ randomKey: getRandomKey() });
        }}
        onError={(errors, fieldsValue) => {
          this.formData = fieldsValue;
          this.setState({ randomKey: getRandomKey(), isOpen: true });
        }}
        onCancel={() => {
          this.setState({
            isOpen: false,
          });
        }}
      >
        {this.props.children}
      </SearchFormComp>
    );

    return (
      <div style={{ fontSize: 14, whiteSpace: 'normal' }}>
        <Popover visible={this.state.isOpen}
                 onVisibleChange={visible => {
                   // if (visible === false && false === this.props.multiAct) {
                   //   // 如果必填字段为空，则不关闭搜索浮层
                   //   this.searchRef.validateForm(() => {
                   //     this.setState({ isOpen: false });
                   //   }, () => {
                   //     this.setState({ isOpen: true });
                   //   });
                   // } else {
                     this.setState({ isOpen: visible });
                   // }
                 }}
                 placement={'bottomLeft'}
                 overlayStyle={{ width: 450, zIndex: this.popoverZIndex }}
                 content={(
                   <Spin spinning={true === this.props.loading}>
                     {formContent}
                   </Spin>
                 )}
                 trigger={'click'}
                 {...popoverProps}
        >

          {
            this.props.customBtn ? this.props.customBtn : (
              <a href={'javascript:;'} className={'mr8'}>
                筛选条件 <Icon type="right"/>
              </a>
            )
          }
          {
            this.props.needPrev && map(previewFields, (v, k) => {
              let pre = -1 === v.text.indexOf(`${v.label}：`) ? `${v.label}：` : '';
              return (
                <Tag key={k} style={tagStyle}
                     title={`${pre}${v.text}`}
                     closable={true}
                     onClose={this.deleteSearchFields.bind(this, v.fieldNames)}>
                  <span style={tagSpanStyle}>{v.text || ''}</span>
                </Tag>
              );
            })
          }
        </Popover>
      </div>
    );
  }
}

SearchComp.defaultProps = {
  formData: null, // Object 默认的表单数据
  customBtn: null, // ReactComponent 自定义的按钮
  needPrev: true, // Boolean 是否需要回显搜索条件
  multiAct: false, // Boolean 是否用于 批量操作（如 批量打印、批量导出）
  getPreviewData: null, // Function 设置回显的数据，如：
                        // (formData) => {
                        //    return [{
                        //       label: '会计期间',
                        //       fieldNames: 'beginPeriod;endPeriod',
                        //       text: `${formData.beginPeriod.name} 至 ${formData.endPeriod.name}`
                        //   }];
                        // }
  defaultOpen: false, // Boolean 是否默认打开搜索表单
  onOk: null, // Function 确认搜索的回调；如：(values: 用于请求接口的数据对象, originalValues: 表单的原始数据对象) => {}
  popoverProps: {}, // Object (选传) Popover 组件的属性值
};

export default SearchComp;
